package club.caihappy.store.service.impl;

import club.caihappy.store.entity.Address;
import club.caihappy.store.entity.User;
import club.caihappy.store.mapper.AddressMapper;
import club.caihappy.store.mapper.DistrictMapper;
import club.caihappy.store.mapper.UserMapper;
import club.caihappy.store.service.IAddressService;
import club.caihappy.store.service.IDistrictService;
import club.caihappy.store.service.IUserService;
import club.caihappy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 收货地址模块业务层的实现类
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private IDistrictService districtService;

    @Value("${user.address.max-count}")
    private Integer maxCount;


    //增加一条收货地址
    public void addNewAddress(Integer uid, String username, Address address) {
        //判断收获地址的数量是否超出上限
        Integer count = addressMapper.countByUid(uid);
        if (count >= maxCount) {
            throw new AddressCountLimitException("用户收货地址数量超出上限: " + maxCount + "条");
        }
        //依赖于IDistrictService接口
        address.setProvinceName(districtService.findNameByCode(address.getProvinceCode()));
        address.setCityName(districtService.findNameByCode(address.getCityCode()));
        address.setAreaName(districtService.findNameByCode(address.getAreaCode()));


        address.setUid(uid);
        //第一次添加的收获地址为默认收货地址
        address.setIsDefault(count == 0 ? 1 : 0);
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());
        Integer row = addressMapper.insert(address);
        if (row != 1) {
            throw new InsertException("插入用户收货地址时发生未知异常");
        }

    }

    @Override
    public List<Address> getByUid(Integer uid) {
        List<Address> list = addressMapper.findByUid(uid);
        for (Address address : list) {
            address.setAreaCode(null);
            address.setCityCode(null);
            address.setProvinceCode(null);
            address.setTel(null);
            address.setCreatedTime(null);
            address.setCreatedUser(null);
            address.setModifiedTime(null);
            address.setModifiedUser(null);
        }
        return list;
    }

    @Transactional
    @Override
    public void setDefault(Integer aid, Integer uid, String modifiedUser) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("收货地址不存在");
        }
        //检查当前获取到的收货地址的归属
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法数据访问");
        }
        Integer rows = addressMapper.updateNonDefault(uid);
        if (rows < 1) {
            throw new UpdateException("更新数据时产生未知异常");
        }
        rows = addressMapper.updateDefaultByAid(aid, modifiedUser, new Date());
        if (rows != 1) {
            throw new UpdateException("更新数据时产生未知异常");
        }

    }

    @Override
    public void deleteAddress(Integer aid, Integer uid, String username) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("收货地址不存在");
        }
        //检查当前获取到的收货地址的归属
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法数据访问");
        }

        Integer rows = addressMapper.deleteByAid(aid);
        if (rows != 1) {
            throw new DeleteException("删除收货地址时产生未知异常");
        }
        /*删除默认地址后自动设置新的默认地址（可不加）*/
//        if (addressMapper.countByUid(uid) == 0) {
//            return;
//        }
//        //如果删除的是默认收货地址，就将该用户最后修改的收货地址设为默认
//        if (address.getIsDefault() == 1) {
//            Address lastModifiedAddress = addressMapper.findLastModified(uid);
//            Integer row = addressMapper.updateDefaultByAid(lastModifiedAddress.getAid(), username, new Date());
//            if (row != 1) {
//                throw new UpdateException("更新数据时产生未知异常");
//            }
//        }

    }

    @Override
    public Address getByAid(Integer aid, Integer uid) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("收货地址数据不存在");
        }
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法数据访问");
        }
        return address;
    }


}
